package service

import (
	"time"

	"gitee.com/liumou_site/go-network-monitoring/types"
	"gitee.com/liumou_site/go-network-monitoring/utils"
)

// NetworkResponseBuilder 网络响应构建器
type NetworkResponseBuilder struct{}

// NewNetworkResponseBuilder 创建网络响应构建器实例
func NewNetworkResponseBuilder() *NetworkResponseBuilder {
	return &NetworkResponseBuilder{}
}

// BuildNetworkAPIResponse 构建网络API响应
func (rb *NetworkResponseBuilder) BuildNetworkAPIResponse(allStats map[string]*types.NetData, speedStats map[string]*types.SpeedData) types.NetworkAPIResponse {
	// 计算总速率和流量
	var totalDownloadSpeed, totalUploadSpeed float64
	var totalDownloadBytes, totalUploadBytes uint64

	for _, stats := range speedStats {
		totalDownloadSpeed += stats.DownloadSpeed
		totalUploadSpeed += stats.UploadSpeed
	}

	for _, stats := range allStats {
		totalDownloadBytes += stats.TotalDownload
		totalUploadBytes += stats.TotalUpload
	}

	// 构建响应数据
	response := types.NetworkAPIResponse{
		Interfaces: make(map[string]interface{}),
		Summary: types.NetworkSummary{
			TotalInterfaces:    len(allStats),
			ActiveInterfaces:   len(speedStats),
			VirtualInterfaces:  0,
			PhysicalInterfaces: 0,
			TotalDownloadSpeed: utils.CalculateSpeedMbps(totalDownloadSpeed),
			TotalUploadSpeed:   utils.CalculateSpeedMbps(totalUploadSpeed),
			TotalDownloadGB:    utils.CalculateGB(totalDownloadBytes),
			TotalUploadGB:      utils.CalculateGB(totalUploadBytes),
			UpdateTime:         time.Now().Format("2006-01-02 15:04:05"),
		},
	}

	// 填充每个接口的数据
	virtualCount := 0
	physicalCount := 0

	for name, stats := range allStats {
		if stats.IsVirtual {
			virtualCount++
		} else {
			physicalCount++
		}

		response.Interfaces[name] = map[string]interface{}{
			"stats":     stats,
			"speed":     speedStats[name],
			"isVirtual": stats.IsVirtual,
		}
	}

	// 更新统计信息
	response.Summary.VirtualInterfaces = virtualCount
	response.Summary.PhysicalInterfaces = physicalCount

	return response
}

// BuildSpeedAPIResponse 构建SSE API响应
func (rb *NetworkResponseBuilder) BuildSpeedAPIResponse(allStats map[string]*types.NetData, speedStats map[string]*types.SpeedData) types.SpeedAPIResponse {
	speedData := make(types.SpeedAPIResponse)

	for name, stats := range allStats {
		if speed, exists := speedStats[name]; exists {
			receivedMbps := utils.CalculateSpeedMbps(speed.DownloadSpeed)
			sentMbps := utils.CalculateSpeedMbps(speed.UploadSpeed)
			totalReceivedGB := utils.CalculateGB(stats.TotalDownload)
			totalSentGB := utils.CalculateGB(stats.TotalUpload)
			packetLoss := float64(stats.TotalDropped) * 100 / float64(stats.TotalDownload+stats.TotalUpload+1)

			speedData[name] = types.SpeedInfo{
				ReceivedMbps:    receivedMbps,
				SentMbps:        sentMbps,
				TotalReceivedGB: totalReceivedGB,
				TotalSentGB:     totalSentGB,
				PacketLoss:      packetLoss,
				IsVirtual:       stats.IsVirtual,
				// 格式化字符串字段
				ReceivedMbpsText:  utils.FormatSpeed(speed.DownloadSpeed),
				SentMbpsText:      utils.FormatSpeed(speed.UploadSpeed),
				TotalReceivedText: utils.FormatBytesFloat(float64(stats.TotalDownload)),
				TotalSentText:     utils.FormatBytesFloat(float64(stats.TotalUpload)),
				PacketLossText:    utils.FormatPercentage(packetLoss),
			}
		}
	}

	return speedData
}

// BuildInterfaceListResponse 构建网卡列表响应
func (rb *NetworkResponseBuilder) BuildInterfaceListResponse(interfaces []*types.InterfaceInfo) types.InterfaceListResponse {
	// 计算统计信息
	var totalCount, physicalCount, virtualCount, activeCount int
	for _, iface := range interfaces {
		totalCount++
		if iface.IsVirtual {
			virtualCount++
		} else {
			physicalCount++
		}
		if iface.Status == "active" {
			activeCount++
		}
	}

	// 转换指针数组为值数组
	interfaceList := make([]types.InterfaceInfo, len(interfaces))
	for i, iface := range interfaces {
		interfaceList[i] = *iface
	}

	return types.InterfaceListResponse{
		Interfaces: interfaceList,
		Count:      totalCount,
		Summary: types.InterfaceListSummary{
			TotalInterfaces:    totalCount,
			PhysicalInterfaces: physicalCount,
			VirtualInterfaces:  virtualCount,
			ActiveInterfaces:   activeCount,
			UpdateTime:         time.Now().Format("2006-01-02 15:04:05"),
		},
	}
}
